// 交通工具监测页面专用脚本
document.addEventListener('DOMContentLoaded', function() {
    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const transportType = urlParams.get('type');
    
    // 根据交通工具类型加载相应的监测界面
    loadTransportMonitor(transportType);
    
    // 初始化视频监控模拟
    initVideoMonitoring();
    
    // 初始化异常行为检测
    initAnomalyDetection();
    
    // 初始化实时数据更新
    initRealTimeData();
});

// 加载交通工具监测界面
function loadTransportMonitor(type) {
    const monitorTitle = document.querySelector('.monitor-title');
    const monitorDescription = document.querySelector('.monitor-description');
    
    if (monitorTitle && monitorDescription) {
        // 根据类型设置标题和描述
        switch(type) {
            case 'bus':
                monitorTitle.textContent = '公交车异常行为监测';
                monitorDescription.textContent = '实时监测公交车内司机和乘客行为，检测疲劳驾驶、分心驾驶、乘客异常行为等安全隐患。';
                break;
            case 'subway':
                monitorTitle.textContent = '地铁异常行为监测';
                monitorDescription.textContent = '实时监测地铁车厢内乘客行为，检测可疑物品、异常行为等安全隐患。';
                break;
            case 'highspeed':
                monitorTitle.textContent = '高铁异常行为监测';
                monitorDescription.textContent = '实时监测高铁车厢内乘客行为，保障旅客安全。';
                break;
            case 'train':
                monitorTitle.textContent = '火车异常行为监测';
                monitorDescription.textContent = '实时监测火车车厢内乘客行为，保障旅客安全。';
                break;
            default:
                monitorTitle.textContent = '交通工具异常行为监测';
                monitorDescription.textContent = '实时监测交通工具内司机和乘客行为，保障出行安全。';
        }
    }
    
    // 加载相应的监控摄像头列表
    loadCameraList(type);
}

// 加载监控摄像头列表
function loadCameraList(type) {
    const cameraListContainer = document.querySelector('.camera-list');
    
    if (cameraListContainer) {
        // 清空现有列表
        cameraListContainer.innerHTML = '';
        
        // 根据类型生成不同数量的摄像头
        let cameraCount = 0;
        switch(type) {
            case 'bus':
                cameraCount = 6;
                break;
            case 'subway':
                cameraCount = 8;
                break;
            case 'highspeed':
                cameraCount = 10;
                break;
            case 'train':
                cameraCount = 12;
                break;
            default:
                cameraCount = 6;
        }
        
        // 生成摄像头列表
        for (let i = 1; i <= cameraCount; i++) {
            const cameraItem = document.createElement('div');
            cameraItem.className = 'camera-item';
            cameraItem.setAttribute('data-id', i);
            
            let cameraName = '';
            if (type === 'bus') {
                cameraName = i <= 2 ? `${i}号公交车司机摄像头` : `${i-2}号公交车乘客区域摄像头`;
            } else if (type === 'subway') {
                cameraName = `${i}号地铁车厢摄像头`;
            } else if (type === 'highspeed') {
                cameraName = `${i}号高铁车厢摄像头`;
            } else if (type === 'train') {
                cameraName = `${i}号火车车厢摄像头`;
            } else {
                cameraName = `${i}号摄像头`;
            }
            
            cameraItem.innerHTML = `
                <div class="camera-info">
                    <span class="camera-name">${cameraName}</span>
                    <span class="camera-status ${Math.random() > 0.2 ? 'online' : 'offline'}">
                        ${Math.random() > 0.2 ? '在线' : '离线'}
                    </span>
                </div>
                <div class="camera-actions">
                    <button class="btn-view">查看</button>
                    <button class="btn-history">历史</button>
                </div>
            `;
            
            cameraListContainer.appendChild(cameraItem);
        }
        
        // 添加摄像头点击事件
        addCameraEvents();
    }
}

// 添加摄像头事件
function addCameraEvents() {
    const cameraItems = document.querySelectorAll('.camera-item');
    
    cameraItems.forEach(item => {
        const viewBtn = item.querySelector('.btn-view');
        const historyBtn = item.querySelector('.btn-history');
        const cameraId = item.getAttribute('data-id');
        
        if (viewBtn) {
            viewBtn.addEventListener('click', function() {
                // 显示实时监控视频
                showLiveVideo(cameraId);
            });
        }
        
        if (historyBtn) {
            historyBtn.addEventListener('click', function() {
                // 显示历史监控记录
                showHistoryRecords(cameraId);
            });
        }
    });
}

// 显示实时监控视频
function showLiveVideo(cameraId) {
    const videoContainer = document.querySelector('.video-container');
    const videoTitle = document.querySelector('.video-title');
    
    if (videoContainer && videoTitle) {
        // 更新视频标题
        videoTitle.textContent = `摄像头 #${cameraId} 实时监控`;
        
        // 清空现有视频
        videoContainer.innerHTML = '';
        
        // 创建视频元素（这里使用模拟视频）
        const videoElement = document.createElement('div');
        videoElement.className = 'video-simulation';
        videoElement.innerHTML = `
            <div class="video-overlay">
                <div class="video-info">
                    <span class="camera-id">摄像头 #${cameraId}</span>
                    <span class="timestamp">${new Date().toLocaleString()}</span>
                </div>
                <div class="detection-box" style="display: none;"></div>
            </div>
            <div class="video-placeholder">视频加载中...</div>
        `;
        
        videoContainer.appendChild(videoElement);
        
        // 模拟视频加载
        setTimeout(() => {
            const placeholder = videoElement.querySelector('.video-placeholder');
            if (placeholder) {
                placeholder.textContent = '实时视频监控中（模拟）';
                
                // 随机触发异常行为检测
                simulateAnomalyDetection(videoElement);
            }
        }, 1500);
    }
}

// 显示历史监控记录
function showHistoryRecords(cameraId) {
    const videoContainer = document.querySelector('.video-container');
    const videoTitle = document.querySelector('.video-title');
    
    if (videoContainer && videoTitle) {
        // 更新视频标题
        videoTitle.textContent = `摄像头 #${cameraId} 历史记录`;
        
        // 清空现有视频
        videoContainer.innerHTML = '';
        
        // 创建历史记录列表
        const historyList = document.createElement('div');
        historyList.className = 'history-list';
        
        // 生成一些模拟的历史记录
        const today = new Date();
        for (let i = 0; i < 5; i++) {
            const recordDate = new Date(today);
            recordDate.setHours(today.getHours() - i * 2);
            
            const historyItem = document.createElement('div');
            historyItem.className = 'history-item';
            
            const hasAnomaly = Math.random() > 0.6;
            historyItem.innerHTML = `
                <div class="history-time">${recordDate.toLocaleString()}</div>
                <div class="history-info">
                    <span class="history-status ${hasAnomaly ? 'anomaly' : 'normal'}">
                        ${hasAnomaly ? '检测到异常' : '正常'}
                    </span>
                    ${hasAnomaly ? '<span class="history-detail">点击查看详情</span>' : ''}
                </div>
            `;
            
            if (hasAnomaly) {
                historyItem.addEventListener('click', function() {
                    // 显示异常行为详情
                    showAnomalyDetails(cameraId, recordDate);
                });
            }
            
            historyList.appendChild(historyItem);
        }
        
        videoContainer.appendChild(historyList);
    }
}

// 显示异常行为详情
function showAnomalyDetails(cameraId, timestamp) {
    const videoContainer = document.querySelector('.video-container');
    const videoTitle = document.querySelector('.video-title');
    
    if (videoContainer && videoTitle) {
        // 更新视频标题
        videoTitle.textContent = `异常行为详情 - 摄像头 #${cameraId} - ${timestamp.toLocaleString()}`;
        
        // 清空现有内容
        videoContainer.innerHTML = '';
        
        // 创建异常详情
        const anomalyDetails = document.createElement('div');
        anomalyDetails.className = 'anomaly-details';
        
        // 随机选择异常类型
        const anomalyTypes = [
            '司机疲劳驾驶',
            '司机分心驾驶',
            '乘客异常行为',
            '车内可疑物品',
            '车辆超载'
        ];
        const anomalyType = anomalyTypes[Math.floor(Math.random() * anomalyTypes.length)];
        
        // 生成详情内容
        anomalyDetails.innerHTML = `
            <div class="anomaly-video">
                <div class="video-simulation">
                    <div class="video-overlay">
                        <div class="video-info">
                            <span class="camera-id">摄像头 #${cameraId}</span>
                            <span class="timestamp">${timestamp.toLocaleString()}</span>
                        </div>
                        <div class="detection-box" style="display: block; top: 40%; left: 30%; width: 40%; height: 30%;">
                            <span>${anomalyType}</span>
                        </div>
                    </div>
                    <div class="video-placeholder">异常行为视频回放（模拟）</div>
                </div>
            </div>
            <div class="anomaly-info">
                <h3>异常行为分析</h3>
                <div class="info-item">
                    <span class="label">异常类型:</span>
                    <span class="value">${anomalyType}</span>
                </div>
                <div class="info-item">
                    <span class="label">检测时间:</span>
                    <span class="value">${timestamp.toLocaleString()}</span>
                </div>
                <div class="info-item">
                    <span class="label">置信度:</span>
                    <span class="value">${Math.floor(Math.random() * 20) + 80}%</span>
                </div>
                <div class="info-item">
                    <span class="label">处理状态:</span>
                    <span class="value status-pending">待处理</span>
                </div>
                <div class="actions">
                    <button class="btn-process">标记为已处理</button>
                    <button class="btn-export">导出报告</button>
                </div>
            </div>
        `;
        
        videoContainer.appendChild(anomalyDetails);
        
        // 添加按钮事件
        const processBtn = anomalyDetails.querySelector('.btn-process');
        const exportBtn = anomalyDetails.querySelector('.btn-export');
        
        if (processBtn) {
            processBtn.addEventListener('click', function() {
                const statusElement = anomalyDetails.querySelector('.status-pending');
                if (statusElement) {
                    statusElement.textContent = '已处理';
                    statusElement.className = 'value status-processed';
                }
                this.disabled = true;
            });
        }
        
        if (exportBtn) {
            exportBtn.addEventListener('click', function() {
                alert('报告已导出（模拟）');
            });
        }
    }
}

// 模拟异常行为检测
function simulateAnomalyDetection(videoElement) {
    if (!videoElement) return;
    
    const detectionBox = videoElement.querySelector('.detection-box');
    
    if (detectionBox) {
        // 随机决定是否触发异常检测
        setInterval(() => {
            if (Math.random() > 0.7) {
                // 显示检测框
                detectionBox.style.display = 'block';
                
                // 随机位置和大小
                const top = Math.floor(Math.random() * 60) + 20;
                const left = Math.floor(Math.random() * 60) + 20;
                const width = Math.floor(Math.random() * 30) + 20;
                const height = Math.floor(Math.random() * 30) + 20;
                
                detectionBox.style.top = `${top}%`;
                detectionBox.style.left = `${left}%`;
                detectionBox.style.width = `${width}%`;
                detectionBox.style.height = `${height}%`;
                
                // 随机选择异常类型
                const anomalyTypes = [
                    '司机疲劳驾驶',
                    '司机分心驾驶',
                    '乘客异常行为',
                    '可疑物品',
                    '异常行为'
                ];
                const anomalyType = anomalyTypes[Math.floor(Math.random() * anomalyTypes.length)];
                detectionBox.innerHTML = `<span>${anomalyType}</span>`;
                
                // 触发告警
                triggerAlarm(anomalyType);
                
                // 3秒后隐藏
                setTimeout(() => {
                    detectionBox.style.display = 'none';
                }, 3000);
            }
        }, 10000); // 每10秒检测一次
    }
}

// 触发告警
function triggerAlarm(anomalyType) {
    const alertsContainer = document.querySelector('.alerts-container');
    
    if (alertsContainer) {
        // 创建新告警
        const alertItem = document.createElement('div');
        alertItem.className = 'alert-item new';
        
        // 当前时间
        const now = new Date();
        const timeString = now.toLocaleTimeString();
        
        // 告警内容
        alertItem.innerHTML = `
            <div class="alert-time">${timeString}</div>
            <div class="alert-content">
                <div class="alert-type">检测到${anomalyType}</div>
                <div class="alert-actions">
                    <button class="btn-view-alert">查看</button>
                    <button class="btn-ignore">忽略</button>
                </div>
            </div>
        `;
        
        // 添加到告警容器
        alertsContainer.prepend(alertItem);
        
        // 添加告警事件
        const viewBtn = alertItem.querySelector('.btn-view-alert');
        const ignoreBtn = alertItem.querySelector('.btn-ignore');
        
        if (viewBtn) {
            viewBtn.addEventListener('click', function() {
                // 查看告警详情
                alert(`查看${anomalyType}告警详情（模拟）`);
                alertItem.classList.remove('new');
            });
        }
        
        if (ignoreBtn) {
            ignoreBtn.addEventListener('click', function() {
                // 忽略告警
                alertItem.remove();
            });
        }
        
        // 5秒后移除新告警样式
        setTimeout(() => {
            alertItem.classList.remove('new');
        }, 5000);
        
        // 限制告警数量，最多显示10条
        const alertItems = alertsContainer.querySelectorAll('.alert-item');
        if (alertItems.length > 10) {
            alertItems[alertItems.length - 1].remove();
        }
    }
}

// 初始化异常行为检测
function initAnomalyDetection() {
    console.log('异常行为检测系统已初始化');
}

// 初始化实时数据更新
function initRealTimeData() {
    // 更新实时统计数据
    updateStatistics();
    
    // 定期更新数据
    setInterval(updateStatistics, 5000);
}

// 更新统计数据
function updateStatistics() {
    const statItems = document.querySelectorAll('.stat-item .value');
    
    statItems.forEach(item => {
        // 获取当前值
        const currentValue = parseInt(item.textContent);
        
        // 随机变化值
        const variation = Math.floor(Math.random() * 5) - 2; // -2 到 2 的随机变化
        const newValue = Math.max(0, currentValue + variation);
        
        // 更新值
        item.textContent = newValue;
        
        // 如果值增加，添加增加动画
        if (variation > 0) {
            item.classList.add('increased');
            setTimeout(() => {
                item.classList.remove('increased');
            }, 1000);
        }
        
        // 如果值减少，添加减少动画
        if (variation < 0) {
            item.classList.add('decreased');
            setTimeout(() => {
                item.classList.remove('decreased');
            }, 1000);
        }
    });
}

// 初始化图表
function initCharts() {
    // 这里可以使用图表库如Chart.js来创建图表
    // 由于是模拟，这里只添加一个占位符
    console.log('图表初始化（模拟）');
}

// 导出报告
function exportReport(data) {
    // 模拟导出报告功能
    console.log('导出报告', data);
    return true;
}

// 处理异常事件
function processAnomaly(anomalyId, action) {
    // 模拟处理异常事件
    console.log(`处理异常事件 #${anomalyId}，操作: ${action}`);
    return true;
}

// 添加标记
function addMarker(type, position, description) {
    // 模拟在地图上添加标记
    console.log(`添加标记: 类型=${type}, 位置=${position}, 描述=${description}`);
    return true;
}

// 初始化实时位置追踪
function initLocationTracking() {
    // 模拟实时位置追踪
    console.log('实时位置追踪已初始化');
    
    // 模拟位置更新
    setInterval(() => {
        // 随机生成新位置
        const newLat = 39.9 + (Math.random() - 0.5) * 0.1;
        const newLng = 116.4 + (Math.random() - 0.5) * 0.1;
        
        // 更新位置显示
        updateVehicleLocation(newLat, newLng);
    }, 3000);
}

// 更新车辆位置
function updateVehicleLocation(lat, lng) {
    const locationElement = document.querySelector('.vehicle-location');
    
    if (locationElement) {
        locationElement.textContent = `位置: ${lat.toFixed(6)}, ${lng.toFixed(6)}`;
    }
}

// 初始化设备状态监控
function initDeviceMonitoring() {
    // 模拟设备状态监控
    console.log('设备状态监控已初始化');
    
    // 定期更新设备状态
    setInterval(() => {
        updateDeviceStatus();
    }, 8000);
}

// 更新设备状态
function updateDeviceStatus() {
    const deviceItems = document.querySelectorAll('.device-item');
    
    deviceItems.forEach(item => {
        // 随机决定设备状态
        const statusTypes = ['正常', '警告', '错误', '离线'];
        const statusWeights = [0.7, 0.15, 0.1, 0.05]; // 权重，使正常状态出现概率更高
        
        // 根据权重随机选择状态
        let random = Math.random();
        let statusIndex = 0;
        let cumulativeWeight = 0;
        
        for (let i = 0; i < statusWeights.length; i++) {
            cumulativeWeight += statusWeights[i];
            if (random < cumulativeWeight) {
                statusIndex = i;
                break;
            }
        }
        
        const status = statusTypes[statusIndex];
        const statusElement = item.querySelector('.device-status');
        
        if (statusElement) {
            // 移除所有状态类
            statusElement.classList.remove('status-normal', 'status-warning', 'status-error', 'status-offline');
            
            // 添加新状态类
            statusElement.textContent = status;
            
            switch (status) {
                case '正常':
                    statusElement.classList.add('status-normal');
                    break;
                case '警告':
                    statusElement.classList.add('status-warning');
                    break;
                case '错误':
                    statusElement.classList.add('status-error');
                    break;
                case '离线':
                    statusElement.classList.add('status-offline');
                    break;
            }
        }
    });
}

// 初始化事件日志
function initEventLog() {
    // 模拟事件日志
    console.log('事件日志已初始化');
    
    // 定期添加新事件
    setInterval(() => {
        addEventLog();
    }, 15000);
}

// 添加事件日志
function addEventLog() {
    const logContainer = document.querySelector('.event-log');
    
    if (logContainer) {
        // 事件类型
        const eventTypes = [
            '系统启动',
            '摄像头连接',
            '摄像头断开',
            '检测到异常',
            '告警触发',
            '告警处理',
            '系统更新',
            '用户登录',
            '用户操作'
        ];
        
        // 随机选择事件类型
        const eventType = eventTypes[Math.floor(Math.random() * eventTypes.length)];
        
        // 创建事件日志项
        const logItem = document.createElement('div');
        logItem.className = 'log-item';
        
        // 当前时间
        const now = new Date();
        const timeString = now.toLocaleTimeString();
        
        // 日志内容
        logItem.innerHTML = `
            <div class="log-time">${timeString}</div>
            <div class="log-content">${eventType}</div>
        `;
        
        // 添加到日志容器
        logContainer.prepend(logItem);
        
        // 限制日志数量，最多显示50条
        const logItems = logContainer.querySelectorAll('.log-item');
        if (logItems.length > 50) {
            logItems[logItems.length - 1].remove();
        }
    }
}